﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace CTS.Com.Domain.Helper
{
    public static class XmlHelper
    {
        /// <summary>
        /// Check xml node
        /// </summary>
        /// <param name="item">Object check</param>
        /// <returns>True/False</returns>
        public static bool IsXmlNode(object item)
        {
            // Return value
            return item is XmlNode;
        }

        /// <summary>
        /// Extract xml node to string
        /// </summary>
        /// <param name="node">Xml node</param>
        /// <returns>String xml</returns>
        public static string ExtractString(XmlNode node)
        {
            // Local variable declaration
            var result = string.Empty;

            // Check xml element
            if (node.NodeType == XmlNodeType.Element) {
                foreach (XmlNode child in node.ChildNodes) {
                    if (child.NodeType == XmlNodeType.Text)
                        result += child.Value;
                }
            } else result = node.Value;

            // Return value
            return result;
        }

        /// <summary>
        /// Serialize a xml file
        /// </summary>
        /// <typeparam name="T">Type of object serialize</typeparam>
        /// <param name="filename">Xml file path</param>
        /// <param name="obj">Object serialize</param>
        public static void Serialize<T>(string filename, T obj)
        {
            FileHelper.MakeFile(filename);
            var xs = new XmlSerializer(typeof(T));
            using (var wr = new StreamWriter(filename)) {
                xs.Serialize(wr, obj);
            }
        }

        /// <summary>
        /// Deserialize a xml file
        /// </summary>
        /// <typeparam name="T">Type of object deserialize</typeparam>
        /// <param name="filename">Xml file path</param>
        /// <returns>Object deserialize</returns>
        public static T Deserialize<T>(string filename) where T : new()
        {
            if (!File.Exists(filename)) return new T();
            var xs = new XmlSerializer(typeof(T));
            using (var rd = new StreamReader(filename)) {
                return (T)xs.Deserialize(rd);
            }
        }

        /// <summary>
        /// Deserialize a xml file
        /// </summary>
        /// <typeparam name="T">Type of object deserialize</typeparam>
        /// <param name="stream">Xml stream</param>
        /// <returns>Object deserialize</returns>
        public static T Deserialize<T>(Stream stream)
        {
            var xs = new XmlSerializer(typeof(T));
            using (var rd = new StreamReader(stream)) {
                return (T)xs.Deserialize(rd);
            }
        }
    }
}